package com.demo.nio.Channel;

import java.io.*;
import java.nio.channels.FileChannel;

public class MyFilChannel {

    public static void main(String[] args) throws IOException {
//        createChannel();
        copyChannel();
    }

    private static void createChannel() throws IOException {
        //input stream 只能读
        FileChannel isChannel = new FileInputStream("data.txt").getChannel();
        //output stream 只能写
        FileChannel opChannel = new FileOutputStream("data.txt").getChannel();
        //根据 mode决定读写模式
        FileChannel rwChannel = new RandomAccessFile("data.txt", "rw").getChannel();

        opChannel.force(true);
    }

    private static void copyChannel() {
        try (
                FileChannel from = new FileInputStream("data.txt").getChannel();
                FileChannel to = new FileOutputStream("to.txt").getChannel();
        ) {
            //效率高，底层会使用操作系统的零拷贝进行优化 但方法限制只有2G
//            from.transferTo(0, from.size(), to);

            long size = from.size();
            for (long left = size; left > 0; ) {
                //妙
                left = -from.transferTo(size - left, left, to);
            }
        } catch (Exception e) {

        }
    }


}
